/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool findNode(TreeNode* node,int depth,int value,TreeNode* parent,TreeNode ** recordParent,int & recordDepth)
    {
        if(node == 0)
        {
            return false;
        }
        if(node->val == value)
        {
            *recordParent = parent;
            recordDepth = depth;
            return true;
        }
        //if(node->val != value && node)
        //depth = depth + 1;
        return findNode(node->left,depth + 1,value,node,recordParent,recordDepth)
        || findNode(node->right,depth + 1,value,node,recordParent, recordDepth); 
        

    }
    bool isCousins(TreeNode* root, int x, int y) {
        TreeNode * recordParent =0;int recordDepth=0;

        TreeNode * X_recordParent =0;int X_recordDepth=0;
        TreeNode * Y_recordParent =0;int Y_recordDepth=0;
        if(findNode(root,0,x,0,&recordParent,recordDepth))
        {
            X_recordParent = recordParent;
            X_recordDepth = recordDepth;
        }
        else
        {
            return false;
        }
        if(findNode(root,0,y,0,&recordParent,recordDepth))
        {
            Y_recordParent = recordParent;
            Y_recordDepth = recordDepth;
        }
        else
        {
            return false;
        }

        if(X_recordDepth == Y_recordDepth && X_recordParent != Y_recordParent)
        {
            return true;
        }
        return false;
    }
};